package org.example;

import java.security.Principal;
import java.util.concurrent.*;

public class TicketSeller2 {
    //票的总数
    private static int totalTickets = 50;

    public static void main(String[] args) {
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                3,//核心线程数
                5,//最大线程数
                60,//线程等待空闲时间
                TimeUnit.MILLISECONDS,//时间单位
                new ArrayBlockingQueue<>(10),//任务队列
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //创建三个售票员线程
        for (int i = 0; i < 3; i++) {
            //指定售票员编号
            final int sellerId = i+1;
            executorService.submit(new TicketTask(sellerId));
        }
        //关闭线程池
        executorService.shutdown();
    }
    static class TicketTask implements Runnable{
        //售票员编号
        private final int sellerId;

        //构造方法传入编号
        public TicketTask(int sellerId) {
            this.sellerId = sellerId;
        }
        @Override
        public void run() {
            //每个售票员售出的票数
               int TicketAmount = 0;

               //售票员卖光为止
            while (true){
                synchronized (TicketTask.class){
                    if (totalTickets>0){
                        //售出一张票
                        TicketAmount++;
                        totalTickets--;
                        //打印卖票信息
                        System.out.println("售票员"+ sellerId+"售出第"+TicketAmount+"张票");
                        //售票的延迟
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    else{
                        break;
                    }
                }
            }
        }
    }
}
